import React from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import classNames from 'classnames';

import {
  Row,
  Col,
  Panel
} from 'react-bootstrap';

import * as Util from '../common/Util';
import * as Apis from '../config/Apis';
import * as Shell from '../common/Shell';
import Container from '../components/Container';
import * as RecommendActions from '../actions/RecommendActions';

class RecommendApp extends React.Component {

  constructor () {
    super();   
  }

  static propTypes = {
    
  }

  componentDidMount(){
    let searchdate = this.props.location.query.searchdate||"-1";
    this.props.recommendAction.fetchRecommend(searchdate);
    this.props.recommendAction.fetchLastRecommend(searchdate);
  }

  getTodayRecommendTitle(){
    let searchdate = this.props.location.query.searchdate;
    let titleDate = null;
    if (searchdate && searchdate.length) {
      searchdate = searchdate.substring(4);
      titleDate = searchdate.substring(0,2) + "月" + searchdate.substring(2,4) + "日";
    }else{
      titleDate = Util.DateFormater(new Date(), "MM月dd日");
    }
    return  `${titleDate} 盘前股讯`;
  }

  getRenderStyle(val){
    let isHappy = (parseFloat(val) >= 0 ? true : false);
    let happyClass = {
        "text-success": !isHappy,
        "text-danger": isHappy
    };
    let currentClass = classNames( happyClass );

    return currentClass;
  }

  openExternalLink(url){
    let params = { url, showCloseBtn : true , title : '在线行情'};
    Shell.callShellMethod("webViewPlugin", null, null, params );
  }

  renderStockItem(stock){
    let stockcode = stock.stockcode;
    let stockname = stock.stockname;
    let stockarea = Util.getStockArea(stockcode);
    let stockMarketApi = String.format(Apis.stockMarketApi, stockcode, stockarea);
    return (
        <a onClick={this.openExternalLink.bind(this, stockMarketApi)}>
          <h6 className="text-danger">
               {stockname}（{stockcode}）
          </h6> 
        </a>
    );
  }

  renderTitle (recommends){
    return (
       recommends[0].title ?
       <strong className="text-primary">
          { recommends[0].title }
       </strong> 
       :
       null
    );
  }

  renderContent (recommends){
    return (
        recommends.length == 1 && recommends[0].stockname=="" && recommends[0].bz!="" ?
        <p className="text-left text-primary padding-lg padding-left-none" dangerouslySetInnerHTML={{__html: recommends[0].bz}}>
        </p>
        :
        <div>
          {
            recommends.map((item, index)=>{
              return this.renderStockItem(item);
            })
          }
        </div>
    );
  }

  renderComment (recommends){
    return (
           recommends.length > 1 && recommends[0].bz ?
           <div>
              <div className="devider-full"> 
              </div>
              <p className="text-left text-primary" dangerouslySetInnerHTML={{__html: `今日点评：${recommends[0].bz}`}}>
              </p>
           </div>
           :
           null
    );
  }

  renderRecommend(recommends){
    return (
         <div>
            { this.renderTitle(recommends) }

            { this.renderContent(recommends) }

            { this.renderComment(recommends) }
         </div>
    );
  }

  render() {

    let { recommend } = this.props;
    let fromPage = this.props.location.query.from;
    let isGoBack = "Product"; // 坑已经挖好了
    if (fromPage && fromPage === "message") {
        isGoBack = "Message";
    }
    return (
          <Container 
              isGoBack={ isGoBack } 
              isHeader={true} 
              isHeaderMessage={false}
              isFooter={false}  
              headerTitle={ this.getTodayRecommendTitle() }>

              <Panel className="text-center margin-bottom-none">
                  {
                    recommend && recommend.recommend_status === 0 ?
                    <div className="text-center padding-lg">
                        { recommend.message }
                    </div>
                    :
                    recommend && recommend.today && recommend.today.length > 0 ?
                    this.renderRecommend(recommend.today)
                    : 
                    <h6 className="text-danger padding-sm">
                        今日无股讯
                    </h6> 
                  }
                  
              </Panel> 
              <div className="product-container">
                <div className="product-data"> 
                    <Panel header="上交易日回顾" className="panel-thin margin-bottom box-shadow">
                        {

                          recommend && recommend.recommend_last_status === 0 ?
                          <div className="text-center padding-lg">
                              { recommend.message }
                          </div>
                          :
                          recommend && recommend.last && recommend.last.length > 0?
                          recommend.last.map((item, index)=>{
                            return (
                              <Row className="font-normal">
                                <Col xs={6}>
                                    <p>
                                      {item.stockname}（{item.stockcode}）
                                    </p>
                                </Col>
                                <Col xs={6}>
                                    <p>
                                      涨幅：
                                      <span className={this.getRenderStyle(item.profitrate)}>
                                        { parseFloat(item.profitrate).toFixed(2) }%
                                      </span>
                                    </p>
                                </Col>
                              </Row>
                            );
                          })
                          :
                          <h6 className="text-danger text-center padding">
                              上交易日无股讯
                          </h6>  
                        }
                        
                    </Panel> 
                    <Panel header="风险提示" className="panel-thin margin-bottom box-shadow">
                        <strong>该内容为本平台官方免费服务，非平台内策略操作，不消耗任何积分。</strong>
                        <p>
                           本产品仅作证券基础知识普及之用，仅供参考，不构成具体投资建议，且不承诺投资者一定获利，也不对任何人使用本产品所引致的损失负责。
                        </p>
                        <p>
                          特别提示：在日常交易中，对于开盘涨幅超过3％的股票，应注意冲高回落的风险，避免追高。对于持仓股跌幅超过-8％的股票，应该具有止损意识，避免深套。  
                        </p>
                    </Panel>   
                </div>
              </div>
          </Container>
    );
  }
}

export default connect(state => ({
    recommend : state.recommend
}), dispatch => ({
    recommendAction: bindActionCreators(RecommendActions, dispatch)
}))(RecommendApp);
